<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>在线聊天室</title>
    <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
    <!-- 必须先引入vue，  后使用element-ui -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script></head>
<body>
<div id="app">
    <div>
        <input type="text" v-model="sendMessage"/>
        <input type="button" onclick="send()" value="发送">
    </div>
    <hr>
    <div>
        <ul>
            <li v-for="m in messages">
                <!--                <span style="color: #555;">{{m.time}}</span>-->
                <!--                <span>{{m.from}}</span>-->
                <!--                :-->
                <span style="color: red;">{{m.data}}</span>
            </li>
        </ul>
    </div>
</div>
</body>
<script>
    var vue;
    var ws;
    window.onload = () => {
        vue = new Vue({
            el: '#app',
            data: {
                sendMessage:'',
                messages:[]
            }
        });

        ws = new WebSocket('ws://127.0.0.1:8001/chat/twd/1');
        ws.onopen = function(){
            console.log('连接成功.');
        }
        ws.onmessage = function(e){
            //当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
            console.log(e)
            // vue.messages.push(JSON.parse(e.data));
            vue.messages.push(e);
        }
        ws.onerror = function (eerror) {
            //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
            console.log(error);
        };
    };

    function send() {
        ws.send(vue.sendMessage);
    }
</script>
</html>
